import React, { ReactElement, useState, useEffect } from 'react'
import style from './Index.module.less'
import { List, message, Row, Col, Select } from 'antd'
import classNames from 'classnames'
import _ from 'lodash'
import { History } from 'history'
import { getListRequest } from './ajax'
import { awaitWrap } from '@js/tool'
import Item from './components/Item/Index'
import { MeetSchema } from '@components/Schema/MeetSchema'

const { Option } = Select

interface Props {
  history: History
}

// 初始化案件列表
async function initCaseList (setLoading: (v: boolean) => void, setDataSource: (v: MeetSchema[]) => void, status: string): Promise<void> {
  setLoading(true)
  const [e, d] = await awaitWrap(getListRequest(status))
  setLoading(false)
  if (e !== null) {
    await undefined
  } else if (d === null) {
    await message.error('案件列表未返回')
  } else {
    setDataSource(d)
  }
}

const changeFn: (setLoading: (v: boolean) => void, setDataSource: (v: MeetSchema[]) => void, v: string) => void = _.debounce(initCaseList, 500)

function Main ({ history }: Props): ReactElement {
  const [loading, setLoading] = useState(false)
  const [dataSource, setDataSource] = useState<MeetSchema[]>([])
  const [isFixed, setIsFixed] = useState(window.document.documentElement.offsetWidth >= 1280)
  const [status, setStatus] = useState('进行中')

  useEffect(() => {
    changeFn(setLoading, setDataSource, status)
  }, [status])
  useEffect(() => {
    function initFixed (): void {
      setIsFixed(window.document.documentElement.offsetWidth >= 1280)
    }
    window.addEventListener('resize', initFixed)
    return () => {
      window.removeEventListener('resize', initFixed)
    }
  }, [])
  return (
    <div className={style.container}>
      <div className={classNames(style['left-block'], { [style.fixed]: isFixed })}>
        <div className={style['page-title']}>视频庭审</div>
      </div>
      <div className={style.content}>
        <Row gutter={24} className={style.form}>
          <Col span={16}>
          </Col>
          <Col span={8}>
            <Select className={style['status-select']} size='large' value={status} placeholder='请选择' onChange={e => setStatus(e)}>
              <Option value={'进行中'}>进行中</Option>
              <Option value={'已完成'}>已完成</Option>
            </Select>
          </Col>
        </Row>
        <List dataSource={dataSource} loading={loading} locale={{ emptyText: '暂无数据' }} renderItem={d => <Item data={d} history={history} />} />
      </div>
      <div className={classNames(style['right-block'], { [style.fixed]: isFixed })}>
        <div className={style['operate-btn']}>
        </div>
      </div>
    </div>
  )
}

export default Main
